package com.im.app.listener;

import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.exception.ImException;
import org.jim.core.packets.*;
import org.jim.core.utils.JsonKit;
import org.jim.server.JimServerAPI;
import org.jim.server.listener.AbstractImGroupListener;
import org.jim.server.protocol.ProtocolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GroupListener extends AbstractImGroupListener {
    private  static Logger logger = LoggerFactory.getLogger(GroupListener.class);
    @Override
    public void doAfterBind(ImChannelContext imChannelContext, Group group) throws ImException {
        logger.info("群组:{},绑定成功!", JsonKit.toJSONString(group));
        JoinGroupRespBody joinGroupRespBody = JoinGroupRespBody.success();
        //回一条消息，告诉对方进群结果
        joinGroupRespBody.setGroup(group.getGroupId());
        ImPacket respPacket = ProtocolManager.Converter.respPacket(joinGroupRespBody, imChannelContext);
        //发送进房间通知;
//        joinGroupNotify(group, imChannelContext);
        JimServerAPI.send(imChannelContext,respPacket);
    }

    @Override
    public void doAfterUnbind(ImChannelContext imChannelContext, Group group) throws ImException {
        ExitGroupNotifyRespBody exitGroupNotifyRespBody = new ExitGroupNotifyRespBody();
        exitGroupNotifyRespBody.setGroup(group.getGroupId());
        User clientUser = imChannelContext.getSessionContext().getImClientNode().getUser();
        if(clientUser == null) {
            return;
        }
        User notifyUser = new User();
        notifyUser.setUserId(clientUser.getUserId());
        exitGroupNotifyRespBody.setUser(notifyUser);

        RespBody respBody = new RespBody(Command.COMMAND_EXIT_GROUP_NOTIFY_RESP,exitGroupNotifyRespBody);
        ImPacket imPacket = new ImPacket(Command.COMMAND_EXIT_GROUP_NOTIFY_RESP, respBody.toByte());
        JimServerAPI.sendToGroup(group.getGroupId(), imPacket);

    }
}
